#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# made by haven200
# 10:33 23-01-2016

import RPi.GPIO as GPIO 
import time
import signal
import sys
import thread
from basic import write_pid
from basic import remove_pid
from basic import show_message

BEEP_PIN=11
HCSR_PIN=12
hcsr_pid="/var/run/hcsr.pid"
logfile_path="/var/log/hcsr.log"


def init():
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(HCSR_PIN,GPIO.IN)
    GPIO.setup(BEEP_PIN,GPIO.OUT,initial=GPIO.HIGH)

    signal.signal(signal.SIGTERM, onsignal_term)
    write_pid(hcsr_pid)

    pass

def onsignal_term(a,b):
    #show_message('signal_term',logfile_path)
    sys.exit(0)

def beep(number=3):
    for i in range(0,number):
        GPIO.output(BEEP_PIN, GPIO.LOW)
        time.sleep(0.4)
        GPIO.output(BEEP_PIN, GPIO.HIGH)
        time.sleep(0.4)
    #thread.exit_thread()
    
def cleanup():
    GPIO.cleanup()
    remove_pid(hcsr_pid)

def hcsr_detect():
    show_message("hcsr started......",logfile_path)
    try:
        while True:
            if GPIO.input(HCSR_PIN)==True:
                show_message("Someone is closing!",logfile_path)
                #thread.start_new_thread(beep,(2,))
                beep()
                continue
            time.sleep(0.3)
    except KeyboardInterrupt:
        show_message("KeyboardInterrupt!", logfile_path)
    finally:
        show_message("finally",logfile_path)
        cleanup()


if __name__ == '__main__':
    init()
    hcsr_detect()

